package lab.logging;

import java.sql.Connection;
import java.sql.SQLException;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import lab.logging.LoggingUtil.LogMessage;
import ru.ssau.DatabaseHelper;

/**
 *
 * @author Smike
 */
public class LoggingBean implements MessageDrivenBean, MessageListener {

    private MessageDrivenContext context;
    private DataSource datasource;

    public void setMessageDrivenContext(MessageDrivenContext ctx) throws EJBException {
        this.context = ctx;
    }

    public void ejbRemove() throws EJBException {
        // do nothing
    }

    public void onMessage(Message message) {
        Connection connection = getConnection();
        try {
            if (message instanceof ObjectMessage) {
                ObjectMessage msg = (ObjectMessage) message;
                DatabaseHelper.insertLog(connection, (LogMessage) msg.getObject());
            }
        } catch (Exception e) {
            // do nothing, it is logs and no more (and it is only lab)
        }finally {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }

    Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    DataSource getDataSource() {
        if (datasource == null) {
            try {
                datasource = (DataSource) new InitialContext().lookup("oracleDS");
                return datasource;
            } catch (NamingException ex) {
                throw new RuntimeException(ex);
            }
        }
        return datasource;
    }
}
